package com.hmall.order.service.impl;

import com.alibaba.nacos.common.utils.UuidUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmall.common.client.ItemClient;
import com.hmall.common.client.UserClient;
import com.hmall.common.dto.Address;
import com.hmall.common.dto.Item;
import com.hmall.order.mapper.OrderMapper;
import com.hmall.order.pojo.*;
import com.hmall.order.service.IOrderService;
import com.hmall.order.service.OrderDetailService;
import com.hmall.order.service.OrderLogisticsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.UUID;

@Service
public class OrderService extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private ItemClient itemClient;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private OrderLogisticsService orderLogisticsService;
    @Override
    public Long saveOrder(RequestParams requestParams) {
        Address address = userClient.findAddressById(requestParams.getAddressId());
        Item item = itemClient.findByID(requestParams.getItemId());
        Long totalFee = requestParams.getNum()*item.getPrice();
        Order order = new Order();
        order.setStatus(1);
        order.setPaymentType(requestParams.getPaymentType());
        order.setTotalFee(totalFee);
        order.setUserId(IDThreadLocal.getId());
        order.setUserId(2l);
        this.save(order);
        OrderDetail orderDetail = new OrderDetail();
        orderDetail.setItemId(item.getId());
        orderDetail.setOrderId(order.getId());
        orderDetail.setCreateTime(new Date());
        orderDetail.setUpdateTime(new Date());
        orderDetail.setImage(item.getImage());
        orderDetail.setNum(requestParams.getNum());
        orderDetail.setPrice(item.getPrice());
        orderDetail.setSpec(item.getSpec());
        orderDetail.setTitle(item.getName());
        orderDetailService.save(orderDetail);
        OrderLogistics orderLogistics = new OrderLogistics();
        orderLogistics.setCity(address.getCity());
        orderLogistics.setContact(address.getContact());
        orderLogistics.setOrderId(order.getId());
        orderLogistics.setPhone(address.getMobile());
        orderLogistics.setProvince(address.getProvince());
        orderLogistics.setStreet(address.getStreet());
        orderLogistics.setTown(address.getTown());
        orderLogisticsService.save(orderLogistics);
        try {
            itemClient.subStock(requestParams.getItemId(),requestParams.getNum());
        } catch (Exception e) {
            throw new RuntimeException("库存不足");
        }
        return order.getId();
    }
}
